package org.rupa.core.registry.center.controller;

import org.rupa.common.constant.HttpPathConstant;
import org.rupa.common.model.ForwardInfo;
import org.rupa.common.model.HeartbeatBag;
import org.rupa.common.model.ServiceInfo;
import org.rupa.common.util.JsonUtil;
import org.rupa.core.registry.center.RegistryCenter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class RegistryCenterController {
    private Logger log = LoggerFactory.getLogger(RegistryCenterController.class);

    @Autowired
    private RegistryCenter registryCenter;

    @RequestMapping(HttpPathConstant.REGISTER)
    public void register(@RequestBody ServiceInfo serviceInfo) {
        registryCenter.register(serviceInfo);
    }

    @RequestMapping(HttpPathConstant.UNREGISTER)
    public void unregister(@RequestBody ServiceInfo serviceInfo) {
        registryCenter.unregister(serviceInfo);
    }

    @RequestMapping(HttpPathConstant.REFRESH_HEARTBEAT)
    public HeartbeatBag refreshHeartbeat(@RequestBody HeartbeatBag heartbeatBag) {
        return registryCenter.refreshHeartbeat(heartbeatBag);
    }

    @RequestMapping(HttpPathConstant.FORWARD + "/**")
    public Object forward(HttpServletRequest request, @RequestBody(required = false) Object obj) {
        String url = request.getRequestURL().toString();

        log.info("请求接口为: " + url);
        log.info("请求地址: " + request.getRemoteAddr());
        log.info("请求参数: " + JsonUtil.toJson(obj));

        return registryCenter.forward(ForwardInfo.builder().url(url).data(obj).build());
    }
}
